const cookie = require('cookie');
const authenticate = require('../middleware/authenticate');
const httpResponse = require('../modal/response');

class UserController {

    constructor(ctx) {
        this.ctx = ctx;
    }
    
    /**
     * 
     */
    async authenticate() {
       const {request, response} = this.ctx;

       let username = '', password = '';

       try{
            const body = JSON.parse(request.body);
            username = body.username;
            password = body.password;
       }catch(error) {
           return response.badRequest(response, 'body format invalid.');
       }
       
       if(username && password) {
            const [rows] = await this.ctx.db.execute('select id,username from user where username = ? and password = ?', [username ,password]);
            if(rows.length === 1) {
                const value = {id: rows[0].id, username: rows[0].username};
                const token = new authenticate.AuthToken(value);
                token.setStorage();

                this.ctx.set('Set-Cookie', cookie.serialize(token.name, token.key, {
                    path: '/',
                    httpOnly: true,
                    maxAge: 60 * 60 * 24 * 7, // 1 week
                    sameSite: 'Lax'
                }));
                
                response.status = 200;
                response.body = {
                    data: 'ok'
                };
                response.set('Content-Type', 'application/json');
            } else {
                response.status = 401;
                response.body = {
                    data: 'error'
                };
                response.set('Content-Type', 'application/json');
            }
        } else {
            return httpResponse.badRequest(response, 'fields required');
        }
    }
}

module.exports = UserController;